<template>
  <div class="goods-container">
    <!-- 顶部搜索栏 - 闲鱼风格 -->
    <div class="search-bar">
      <div class="search-wrapper">
        <el-input
          v-model="searchQuery"
          placeholder="搜索闲置物品"
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧分类导航 - 闲鱼风格 -->
      <div class="category-sidebar">
        <div class="publish-btn" @click="showPublishDialog">
          <el-button type="primary" size="small" round class="publish-button">
            <el-icon><CirclePlus /></el-icon> 发布闲置
          </el-button>
        </div>
        
        <el-menu
          :default-active="activeCategory"
          class="category-menu"
          @select="handleCategorySelect"
        >
          <el-menu-item
            v-for="category in categories"
            :key="category.categoryId"
            :index="category.categoryId.toString()"
          >
            <template #title>
              <el-icon class="category-icon">
                <component :is="getCategoryIcon(category.categoryId)" />
              </el-icon>
              <span>{{ category.name }}</span>
            </template>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 右侧商品展示 - 闲鱼风格 -->
      <div class="goods-list-container">
        <div v-if="loading" class="loading-indicator">
          <el-icon class="is-loading"><Loading /></el-icon>
          加载中...
        </div>
        
        <div class="goods-list" v-infinite-scroll="loadMore" :infinite-scroll-disabled="noMore">
          <div
            v-for="item in filteredGoods"
            :key="item.id"
            class="goods-item"
            @click="showGoodsDetail(item)"
          >
            <el-card :body-style="{ padding: '0px' }" shadow="hover" class="goods-card">
              <img :src="item.image" class="goods-image" />
              <div class="goods-info">
                <div class="goods-title">{{ item.title }}</div>
                <div class="goods-price">¥{{ item.price }}</div>
                <div class="goods-meta">
                  <span class="goods-location">
                    <el-icon><Location /></el-icon>
                    {{ item.location }}
                  </span>
                  <span class="goods-time">{{ formatTime(item.createdAt) }}</span>
                </div>
                <div class="goods-actions">
                  <el-button type="danger" size="small" @click.stop="addToCart(item)" class="cart-button">
                    <el-icon><ShoppingCart /></el-icon> 想要
                  </el-button>
                </div>
              </div>
            </el-card>
          </div>
        </div>
        
        <div v-if="noMore" class="no-more-text">没有更多了</div>
      </div>
    </div>

    <!-- 发布闲置物品对话框 - 闲鱼风格 -->
    <el-dialog v-model="publishDialogVisible" title="发布闲置" width="80%" class="publish-dialog">
      <el-form :model="newGoodsForm" label-width="100px">
        <el-form-item label="物品标题" required>
          <el-input v-model="newGoodsForm.title" placeholder="请输入物品标题" />
        </el-form-item>
        <el-form-item label="物品分类" required>
          <el-select v-model="newGoodsForm.categoryId" placeholder="请选择分类">
            <el-option
              v-for="category in categories.filter(c => c.categoryId !== 1)"
              :key="category.categoryId"
              :label="category.name"
              :value="category.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物品价格" required>
          <el-input-number v-model="newGoodsForm.price" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="物品描述" required>
          <el-input
            v-model="newGoodsForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入物品详细描述"
          />
        </el-form-item>
        <el-form-item label="上传图片" required>
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleImageChange"
            :limit="3"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="所在位置">
          <el-input v-model="newGoodsForm.location" placeholder="请输入所在位置" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="publishDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="publishGoods">发布</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 商品详情对话框 - 闲鱼风格 -->
    <el-dialog v-model="detailDialogVisible" title="商品详情" width="80%" class="detail-dialog">
      <div v-if="currentGoods" class="goods-detail">
        <div class="detail-images">
          <el-carousel :interval="4000" height="400px">
            <el-carousel-item v-for="(img, index) in currentGoods.images" :key="index">
              <img :src="img" class="detail-image" />
            </el-carousel-item>
          </el-carousel>
        </div>
        <div class="detail-info">
          <h2 class="detail-title">{{ currentGoods.title }}</h2>
          <div class="detail-price">¥{{ currentGoods.price }}</div>
          <div class="detail-meta">
            <span class="meta-item"><el-icon><User /></el-icon> {{ currentGoods.seller }}</span>
            <span class="meta-item"><el-icon><Location /></el-icon> {{ currentGoods.location }}</span>
            <span class="meta-item"><el-icon><View /></el-icon> {{ currentGoods.views }}次浏览</span>
          </div>
          <div class="detail-description">
            <h3>物品描述</h3>
            <p>{{ currentGoods.description }}</p>
          </div>
          <div class="detail-actions">
            <el-button type="danger" size="large" @click="addToCart(currentGoods)" class="action-button">
              <el-icon><ShoppingCart /></el-icon> 想要
            </el-button>
            <el-button type="primary" size="large" @click="buyNow(currentGoods)" class="action-button">
              <el-icon><Wallet /></el-icon> 立即购买
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search, CirclePlus, ShoppingCart, Location, Loading, User, View, Wallet, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 使用通用图标代替特定图标
const getCategoryIcon = (categoryId) => {
  const icons = {
    1: 'CirclePlus', // 全部
    2: 'Iphone',    // 数码
    3: 'Refrigerator', // 家电
    4: 'ShoppingBag',  // 服装
    5: 'Notebook',     // 图书
    6: 'Basketball',   // 运动
    7: 'Present',      // 母婴
    8: 'Box'           // 其他
  }
  return icons[categoryId] || 'Box'
}

// 分类数据
const categories = ref([
  { categoryId: 1, name: '全部闲置', parentId: 0 },
  { categoryId: 2, name: '数码产品', parentId: 0 },
  { categoryId: 3, name: '家用电器', parentId: 0 },
  { categoryId: 4, name: '服装鞋包', parentId: 0 },
  { categoryId: 5, name: '图书音像', parentId: 0 },
  { categoryId: 6, name: '运动户外', parentId: 0 },
  { categoryId: 7, name: '母婴玩具', parentId: 0 },
  { categoryId: 8, name: '其他闲置', parentId: 0 }
])

// 商品数据
const goodsList = ref([])
const displayedGoods = ref([])
const pageSize = 12
const currentPage = ref(1)
const loading = ref(false)
const noMore = ref(false)

// 搜索和筛选
const searchQuery = ref('')
const activeCategory = ref('1') // 默认选中"全部闲置"

// 对话框控制
const publishDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentGoods = ref(null)

// 新商品表单
const newGoodsForm = ref({
  title: '',
  categoryId: null,
  price: 0,
  description: '',
  images: [],
  location: '北京'
})

// 格式化时间显示
const formatTime = (date) => {
  const now = new Date()
  const diff = now - new Date(date)
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(minutes / 60)
  const days = Math.floor(hours / 24)
  
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 30) return `${days}天前`
  return new Date(date).toLocaleDateString()
}

// 初始化商品数据
const initGoodsData = () => {
  // 模拟从后端获取数据
  const mockGoods = []
  const titles = [
    '二手iPhone 13 Pro Max',
    '九成新笔记本电脑',
    '几乎全新的运动鞋',
    '经典文学书籍',
    '家用空气净化器',
    '儿童自行车',
    '专业单反相机',
    '名牌手提包',
    '健身器材套装',
    '游戏主机'
  ]
  const locations = ['北京', '上海', '广州', '深圳', '杭州', '成都']
  
  for (let i = 1; i <= 50; i++) {
    const categoryId = Math.floor(Math.random() * 7) + 2 // 2-8
    mockGoods.push({
      id: i,
      title: titles[Math.floor(Math.random() * titles.length)] + (i % 5 === 0 ? ' ' + i : ''),
      price: (Math.random() * 1000 + 50).toFixed(2),
      description: '这是一个非常好的闲置物品，几乎全新，因为搬家/换新/闲置等原因出售。',
      image: `https://picsum.photos/300/200?random=${i}`,
      images: [
        `https://picsum.photos/600/400?random=${i}1`,
        `https://picsum.photos/600/400?random=${i}2`,
        `https://picsum.photos/600/400?random=${i}3`
      ],
      categoryId,
      location: locations[Math.floor(Math.random() * locations.length)],
      seller: `用户${Math.floor(Math.random() * 1000)}`,
      views: Math.floor(Math.random() * 1000),
      createdAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000)
    })
  }
  
  goodsList.value = mockGoods
  loadMore()
}

// 加载更多商品
const loadMore = () => {
  if (loading.value || noMore.value) return
  
  loading.value = true
  setTimeout(() => {
    const start = (currentPage.value - 1) * pageSize
    const end = start + pageSize
    const filtered = filteredGoods.value
    
    if (start >= filtered.length) {
      noMore.value = true
      loading.value = false
      return
    }
    
    const newItems = filtered.slice(start, end)
    displayedGoods.value = [...displayedGoods.value, ...newItems]
    currentPage.value++
    loading.value = false
    
    if (end >= filtered.length) {
      noMore.value = true
    }
  }, 800)
}

// 根据分类和搜索过滤商品
const filteredGoods = computed(() => {
  let result = goodsList.value
  
  // 按分类过滤
  if (activeCategory.value !== '1') {
    result = result.filter(item => item.categoryId === parseInt(activeCategory.value))
  }
  
  // 按搜索关键词过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(item => 
      item.title.toLowerCase().includes(query) || 
      item.description.toLowerCase().includes(query)
    )
  }
  
  return result
})

// 处理分类选择
const handleCategorySelect = (index) => {
  activeCategory.value = index
  resetGoodsList()
}

// 重置商品列表
const resetGoodsList = () => {
  displayedGoods.value = []
  currentPage.value = 1
  noMore.value = false
  loadMore()
}

// 显示发布对话框
const showPublishDialog = () => {
  publishDialogVisible.value = true
}

// 处理图片上传
const handleImageChange = (file) => {
  // 实际项目中这里应该上传到服务器并获取URL
  // 这里模拟上传成功
  newGoodsForm.value.images.push(URL.createObjectURL(file.raw))
}

// 发布商品
const publishGoods = () => {
  if (!newGoodsForm.value.title || !newGoodsForm.value.categoryId || 
      !newGoodsForm.value.description || newGoodsForm.value.images.length === 0) {
    ElMessage.error('请填写完整信息')
    return
  }
  
  // 模拟添加到商品列表
  const newId = goodsList.value.length + 1
  const newItem = {
    id: newId,
    title: newGoodsForm.value.title,
    price: parseFloat(newGoodsForm.value.price).toFixed(2),
    description: newGoodsForm.value.description,
    image: newGoodsForm.value.images[0],
    images: newGoodsForm.value.images,
    categoryId: newGoodsForm.value.categoryId,
    location: newGoodsForm.value.location || '未知',
    seller: '当前用户',
    views: 0,
    createdAt: new Date()
  }
  
  goodsList.value.unshift(newItem)
  ElMessage.success('发布成功！')
  publishDialogVisible.value = false
  resetGoodsList()
  
  // 重置表单
  newGoodsForm.value = {
    title: '',
    categoryId: null,
    price: 0,
    description: '',
    images: [],
    location: '北京'
  }
}

// 显示商品详情
const showGoodsDetail = (item) => {
  currentGoods.value = { ...item, views: item.views + 1 }
  detailDialogVisible.value = true
}

// 添加到购物车
const addToCart = (item) => {
  ElMessage.success(`已添加 ${item.title} 到想要列表`)
  // 实际项目中这里应该调用API
}

// 立即购买
const buyNow = (item) => {
  ElMessageBox.confirm(
    `确定要购买 ${item.title} 吗？`,
    '确认购买',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('购买成功！')
    detailDialogVisible.value = false
  }).catch(() => {
    ElMessage.info('已取消购买')
  })
}

// 初始化
onMounted(() => {
  initGoodsData()
})
</script>

<style scoped>
.goods-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.search-bar {
  padding: 10px 15px;
  background-color: #ff5000;
  position: sticky;
  top: 0;
  z-index: 100;
}

.search-wrapper {
  max-width: 600px;
  margin: 0 auto;
}

.search-input {
  width: 100%;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.category-sidebar {
  width: 200px;
  background-color: #fff;
  border-right: 1px solid #eee;
  padding: 10px;
  overflow-y: auto;
}

.publish-btn {
  margin-bottom: 20px;
  text-align: center;
}

.publish-button {
  background-color: #ff5000;
  border-color: #ff5000;
  width: 100%;
}

.category-menu {
  border-right: none;
}

.category-icon {
  margin-right: 10px;
}

.goods-list-container {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
}

.goods-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
}

.goods-item {
  cursor: pointer;
  transition: transform 0.2s;
}

.goods-item:hover {
  transform: translateY(-5px);
}

.goods-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.goods-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px 4px 0 0;
}

.goods-info {
  padding: 12px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.goods-title {
  font-size: 14px;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  line-height: 1.4;
  height: 40px;
}

.goods-price {
  color: #ff5000;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}

.goods-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
  margin-bottom: 10px;
}

.goods-actions {
  margin-top: auto;
}

.cart-button {
  width: 100%;
  background-color: #ff5000;
  border-color: #ff5000;
}

.loading-indicator, .no-more-text {
  text-align: center;
  padding: 20px;
  color: #999;
}

.goods-detail {
  display: flex;
  gap: 30px;
}

.detail-images {
  flex: 1;
}

.detail-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.detail-info {
  flex: 1;
  padding: 0 20px;
}

.detail-title {
  font-size: 22px;
  margin-bottom: 15px;
}

.detail-price {
  color: #ff5000;
  font-size: 28px;
  font-weight: bold;
  margin: 15px 0;
}

.detail-meta {
  display: flex;
  gap: 20px;
  color: #666;
  margin-bottom: 20px;
  font-size: 14px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.detail-description {
  margin-top: 30px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.detail-description h3 {
  margin-bottom: 10px;
  font-size: 16px;
}

.detail-actions {
  margin-top: 30px;
  display: flex;
  gap: 15px;
}

.action-button {
  flex: 1;
}

.publish-dialog, .detail-dialog {
  border-radius: 8px;
}

@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }
  
  .category-sidebar {
    width: 100%;
    height: auto;
    overflow-x: auto;
    display: flex;
    padding: 10px 0;
  }
  
  .publish-btn {
    margin: 0 10px;
    min-width: 100px;
  }
  
  .category-menu {
    display: flex;
    flex-direction: row;
    border-bottom: none;
  }
  
  .category-menu .el-menu-item {
    padding: 0 15px;
    height: auto;
    line-height: 1;
  }
  
  .goods-list {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  }
  
  .goods-detail {
    flex-direction: column;
  }
}
</style>